var buttonList=[];
var curDay="";
var flag=true;
var userInfo = {
    
    init : function() {
        //初始化按钮
        setMenuButtonOpermission();
        
        // 初始化事件绑定
        userInfo.evenBind();        
        userInfo.getRoleButtonList();
        var datas = userInfo.getDeptOrgData();
        userInfo.initCombotree($('#userEditDeptId'), datas);
        userInfo.initCombotree($('#userDeptId'), datas);

    },
    evenBind : function() {
        var d = new Date();
     	curDay = d.format("yyyy-MM-dd"); 
     	$('.form_date').datetimepicker({
            language:  'zh-CN',
            todayBtn:  false,
    		autoclose: 1,
    		todayHighlight: 1,
    		startView: 2,
    		minView:2,
    		maxView:2,
    		forceParse: 0
        });
        // ----------------------------------------------------------------------->
        // 添加用户
        // ----------------------------------------------------------------------->
        $('#add').bind('click', function() {
            $('#userAddRoleId').datalist({
                method : 'POST',
                title : '角色选择',
                singleSelect : false,
                valueField : 'roleId',
                textField : 'roleName',
                checkbox : true,
                url : getProjectUrl('/bfs/role/combobox')
            });

            $('#createUserForm').form('clear');
            $('#createUserForm').form('load', {
                uStatus : "1"
            });
            $('input[name=ustatus]').get(1).checked = true;
            $('#createUserDiv').window('open');
        });

        // 取消
        $('#cancelCreateUser').bind('click', function() {
            $('#createUserForm').form('clear');
            $('#createUserDiv').dialog('close');
        });

        // 提交
        $('#submitCreateUser').bind('click', function() {
        	if(flag){
        		flag=false;
        		var loginPwd = $("#loginPW").textbox("getValue");
            	var loginPwdEncryption = userInfo.doSM3(loginPwd);
            	var confirmPW = $("#confirmPW").textbox("getValue");
            	var confirmPWdEncryption = userInfo.doSM3(confirmPW);
    			$("#loginPW").textbox("setValue",loginPwdEncryption);
    			$("#confirmPW").textbox("setValue",confirmPWdEncryption);
                $('#createUserForm').form('submit', {
                    url : getProjectUrl('/bfs/user/add'),
                    onSubmit : function(param) {
                    	flag=true;
                        var _flag = $(this).form('validate');
                        if (!_flag) {
                            return false;
                        }
                        var addLoginName = $('#addLoginName').val();
                        var _valid = userInfo.validLoginName(null, addLoginName);
                        if (!_valid) {
                            ShowMessage('用户登录名称已存在或为空!', 'warning');
                            return false;
                        }
                        var selectRows = $("#userAddRoleId").datalist("getSelections");
                        if (selectRows.length > 0) {
                            var roleIds = [];
                            for (var i = 0; i < selectRows.length; i++) {
                                roleIds[i] = selectRows[i].roleId;
                            }
                            param.roleIds = roleIds;
                        }
                        flag=false;
                        return true;
                    },
                    success : function(data) {
                        data = JSON.parse(data);
                        $.resultHandler(data, function() {
                            $('#createUserForm').form('clear');
                            $('#createUserDiv').dialog('close');
                        });
                        $("#searchUserName").textbox('clear');
                        userInfo.loadData();
                        flag=true;
                    }
                });
        	}
        });

        $('#deletes').bind('click', function() {

            var checkRecord = $('#listDataEx1').datagrid('getChecked');
            if (!checkRecord || checkRecord.length === 0) {
                $.messager.alert('提示', '请先选中记录!', 'warning');
                return;
            }
            var _msg = '您确定要删除选中的' + checkRecord.length + '条记录吗?';
            $.messager.confirm('提示', _msg, function(r) {
                if (r) {
                    var userIds = "";
                    for (var i = 0; i < checkRecord.length; i++) {
                        if (userIds === "") {
                            userIds = checkRecord[i].userid;
                        } else {
                            userIds += "," + checkRecord[i].userid;
                        }
                    }
                    ajaxProcess({
                        url : getProjectUrl('/bfs/user/drop'),
                        data :{
                            userIds : userIds
                        },
                        requestType:"POST",
                        successHandle : function(data) {
                            if(data.result){
                                //ShowMessage(data.message, 'info');
                                $('#listDataEx1').datagrid('reload');
                            }else{
                                if (!isEmpty(data.message)){
                                    ShowMessage(data.message, 'info');
                                    return false;
                                }
                                else
                                {
                                    ShowMessage('操作失败!', 'error');
                                    return false;
                                }
                            }
                        }
                    });
                }
            });

        });
        // ----------------------------------------------------------------------->
        // 初始化用户密码
        // ----------------------------------------------------------------------->
        $('#initPassword').click(function() {
            var checkRecord = $('#listDataEx1').datagrid('getChecked');
            if (!checkRecord || checkRecord.length !== 1) {
                ShowMessage('请选中一条记录!', 'warning');
                return;
            }
            ajaxProcess({
                url : getProjectUrl("/bfs/user/init/password"),
                data :{
                    loginname : checkRecord[0].loginname
                },
                requestType:"POST",
                traditional : true,
                successHandle : function(data) {
                    $.resultHandler(data, function() {
                        $('#setUserMenuForm').form('clear');
                        $('#setUserMenuDiv').dialog('close');
                    });
                }
            });

        });
        
        // 取消编辑用户
        $('#cancelEditUser').bind('click', function() {
            $('#editUserForm').form('clear');
            $('#editUserDiv').dialog('close');
        });

        // 提交编辑用户
        $('#submitEditUser').bind('click', function() {
            $('#editUserForm').form('submit', {
                url : getProjectUrl('/bfs/user/edit'),
                onSubmit : function(param) {
                    var selectRows = $("#userEditRoleId").datalist("getSelections");
                    if (selectRows.length > 0) {
                        var roleIds = [];
                        for (var i = 0; i < selectRows.length; i++) {
                            roleIds[i] = selectRows[i].roleId;
                        }
                        param.roleIds = roleIds;
                    }
                    return $(this).form('validate');
                },
                success : function(data) {
                    data = JSON.parse(data);
                    $.resultHandler(data, function() {
                        $('#editUserForm').form('clear');
                        $('#editUserDiv').dialog('close');
                    });
                    flag=true;
                    $('#listDataEx1').datagrid('reload');
                }
            });
        });
    },
    getRoleButtonList:function(){
       	ajaxProcess({
            url : getProjectUrl("/bfs/configuration/userbuttonlist"),
            data :{
            },
            requestType:"POST",
            async : false,
            successHandle : function(data) {
                buttonList= data;
                userInfo.loadData();
            }
        });
   },
    // ----------------------------------------------------------------------->
    // 修改用户
    // ----------------------------------------------------------------------->
    openEditUserDiv : function(index) {
        var checkRecord = $('#listDataEx1').datagrid('getData').rows[index];
        $('#invalidEditTime').val();
        $('#editUserDiv').window({
            onOpen : function() {
                $('#userEditRoleId').datalist({
                    method : 'POST',
                    title : '角色选择',
                    singleSelect : false,
                    valueField : 'roleId',
                    idField : 'roleId',
                    textField : 'roleName',
                    checkbox : true,
                    url : getProjectUrl('/bfs/role/combobox?userId='+checkRecord.userid+''),
                    onLoadSuccess : function(data) {
                        $('#userEditRoleId').datagrid('unselectAll');
                        $('#userEditRoleId').datagrid('uncheckAll');

                        for(var j=0;j<data.rows.length;j++){
                            var rowIndex = $('#userEditRoleId').datagrid('getRowIndex', data.rows[j]);
                            if(data.rows[j].ischeck>0){
                               $('#userEditRoleId').datagrid('selectRow', rowIndex); 
                            }  
                        }
                       
                    }
                });

                $('#editUserForm').form('load', checkRecord);
             	$('.form_date').datetimepicker('setStartDate', curDay);
            }
        });
        $('#editUserDiv').window('open');
    },
    // 获取部门组织树
    getDeptOrgData : function() {

        var result = [];

        ajaxProcess({
            // url:getProjectUrl('/bfs/dept/treelist'),
            url : getProjectUrl('/bfs/dept/combobox'),
            requestType : 'POST',
            async : false,
            successHandle : function(data) {
                for (var i = 0; i < data.rows.length; i++) {
                    result.push(data.rows[i]);
                }
            }
        });

        return result;
    },
    //sm3加密
    doSM3 : function(msg) {
		var msgData = CryptoJS.enc.Utf8.parse(msg);

		var md;
		var sm3keycur = new SM3Digest();
		msgData = sm3keycur.GetWords(msgData.toString());
		sm3keycur.BlockUpdate(msgData, 0, msgData.length);
		var c3 = new Array(32);
		sm3keycur.DoFinal(c3, 0);
		var hashHex = sm3keycur.GetHex(c3).toString();
		return hashHex.toUpperCase();
	},
    // 初始化树下拉框
    initCombotree : function(DOM, data) {

        DOM.combotree({
            data : data
        })
    },
    // ----------------------------------------------------------------------->
    // 删除用户
    // ----------------------------------------------------------------------->
    openRemoveUserDiv : function(userId) {
        var _msg = '您确定要删除该条记录吗?';
        $.messager.confirm('提示', _msg, function(r) {
            if (r) {
                ajaxProcess({
                    url : getProjectUrl('/bfs/user/drop'),
                    requestType : 'POST',
                    data : {
                        userIds : userId
                    },
                    traditional : true,
                    successHandle : function(data) {
                        if(data.result){
                           // ShowMessage(data.message, 'info');
                            $('#listDataEx1').datagrid('reload');
                        }else{
                            if (!isEmpty(data.message)){
                                ShowMessage(data.message, 'info');
                                return false;
                            }
                            else
                            {
                                ShowMessage('操作失败!', 'error');
                                return false;
                            }
                        }
                    }
                });
            }
        });
    },
    // ----------------------------------------------------------------------->
    // 重置用户密码
    // ----------------------------------------------------------------------->
    editUserPassWDDiv : function(loginname) {
    	var _msg = '您确定要重置密码吗?';
    	$.messager.confirm('提示', _msg, function(r) {
    		if (r) {
    			ajaxProcess({
                    url : getProjectUrl("/bfs/user/init/password"),
                    data :{
                        loginname : loginname
                    },
                    requestType:"POST",
                    traditional : true,
                    successHandle : function(data) {
                        $.resultHandler(data, function() {
                            $('#setUserMenuForm').form('clear');
                            $('#setUserMenuDiv').dialog('close');
                        });
                    }
                });
    		}
    	});
    },
    // 验证用户的名称
    validLoginName : function(_userId, _loginName) {
        var _flag;
        ajaxProcess({
            url : getProjectUrl("/bfs/user/valid"),
            requestType : 'POST',
            data : {
                userid : _userId,
                loginname : _loginName
            },
            async:false,
            successHandle : function(data) {
                _flag = data.result;
            }
        });
        return _flag;
    },
    refreshData : function() {
        userInfo.loadData();
    },
    beforeLoad : function() {
        $('#createUserDiv').dialog('destroy', true);
        $('#editUserDiv').dialog('destroy', true);
        $('#setUserMenuDiv').dialog('destroy', true);
        $('#setUserResourceDiv').dialog('destroy', true);
    },
    // ----------------------------------------------------------------------->
    // 打开设置用户菜单的窗口
    // ----------------------------------------------------------------------->
    openSetUserMenuDiv : function(_userId) {
    	var url=getProjectUrl("/views/bfs/editUserMenu.html");
    	userInfo.openDiv("usermenu"+_userId,"设置用户菜单",url,_userId,500,500);
    },
    loadData : function() {
    	$(".list").show();
		$(".nolist").hide();
        $('#listDataEx1').datagrid({
            url : getProjectUrl('/bfs/user/list'),
            // title:'用户管理',
            queryParams : {
                searchUserName : $.trim($("#searchUserName").val())
            },
            columns : [ [ {
                field : 'ck',
                checkbox : true
            }, {
                field : 'userid',
                title : 'ID',
                width : 100,
                hidden : true          
            }, {
                field : 'loginname',
                title : '用户登录名称',
                width : 100
            }, {
                field : 'username',
                title : '用户真实姓名',
                width : 100
            }, {
                field : 'email',
                title : '邮箱',
                width : 100
            }, {
                field : 'tel',
                title : '手机',
                width : 100
            }, {
                field : 'createtime',
                title : '创建时间',
                width : 100
            }, {
                field : 'ustatus',
                title : '状态',
                width : 100,
                formatter : function(value) {
                    if (value === 1) {
                        return "启用";
                    } else {
                        return "禁用";
                    }
                }
            },{
                field : 'deptName', 
                title : '部门名称',
                width : 100
            }, {
                field : "control",
                title : "操作",
                width : 200,
                align : 'center',
                formatter : function(value, row, index) {
                	var dynacontrol='';
                    var width=750;
                    var height=506;
                    for(var i=0;i<buttonList.length;i++)
                  		{
                    	//dynacontrol += '<a class="menucls" href="javascript:void(0)" onclick="roleInfo.openDiv(\'' + buttonList[i].id + '\',\'' + buttonList[i].buttonName + '\',\'' + buttonList[i].url + '\','+row.roleId+');">'+buttonList[i].buttonName+'</a>';
                        dynacontrol += '<a class="btn-stationrole" href="javascript:void(0)" name='+buttonList[i].buttonCode+' title='+buttonList[i].buttonName+' onclick="userInfo.openDiv(\'button' + +row.userid + '\',\'' + buttonList[i].buttonName + '\',\'' + buttonList[i].url + '\','+row.userid+','+width+',\''+height+'\');"></a>';
                  		}
                     var control = '<span style="height: auto;">';
                     control +=dynacontrol;
                     control += '<a class="btn-edit" href="javascript:void(0)" name="edit" title="编辑" onclick="userInfo.openEditUserDiv(\'' + index +'\');"></a>';
                     control += '<a class="btn-delete" href="javascript:void(0)" name="delete" title="删除" onclick="userInfo.openRemoveUserDiv(\'' + row.userid + '\');"></a>';
                     control += '<a class="btn-resetpwd" href="javascript:void(0)" name="resetPWD" title="重置密码" onclick="userInfo.editUserPassWDDiv(\'' + row.loginname + '\');"></a>';
                     control += '</span>';
                     return control;
                      }
            } ] ],
            rownumbers : true,
            method : 'POST',
            pagination : true,
            pageList : [ 20, 50, 100, 200 ],

            pageSize : 20,
            fitColumns : true,
            onLoadSuccess : function(data) {
                setMenuButtonOpermission();
                
                $('.menucls').linkbutton();
                if(data.rows === null || data.rows.length === 0){
					   $(".list").hide();
					   $(".nolist").css("height", $(".list").outerHeight()).show();	 
				}
            }
        });

    },
    openDiv : function(id,sName,url,userId,width,heigth) {
		openDialogById(id, sName, url+"?userId="+userId, {}, width,heigth);
	}
};
$(function() {
    resetSize();
    userInfo.init();
});

